#!/usr/bin/python

#Created by cheng 2017-04-17
#Import CU 4G Man Data [PYTHON]
#Version 1.0 

import os
import commands
import sys
import logging
import shutil


WORKPATH='/root/work'
LOGPATH=WORKPATH + '/log'
LOGFILE=LOGPATH + '/cu_4g_man_import_coeus.log'

#Logger
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',  
                    datefmt='%Y-%m-%d %H:%M:%S',  
                    filename=LOGFILE,  
                    filemode='w')  
console = logging.StreamHandler()  
console.setLevel(logging.INFO)  
# set print format
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')  
console.setFormatter(formatter)  
#
logging.getLogger('').addHandler(console)  
logger1 = logging.getLogger('myapp.area1')                     
                    

#ORACLE TNS
TNS_NAME='SDS_DEV'
USERNAME='coeus'
PASSWORD='h16aug8v3w'


os.environ['LD_LIBRARY_PATH']=str("/home/instantclient_11_2")
os.environ['ORACLE_HOME']=str("/home/instantclient_11_2")
os.environ['TNS_ADMIN']=str("/home/instantclient_11_2")
os.environ['NLS_LANG']=str("american_america.ZHS16GBK")
os.environ['PATH']=str("$PATH:/home/instantclient_11_2")


SOURCEPATH='/data/coeus/data/cu/'
SOURCEPATH2='/data/coeus/data/4g/'
SOURCEPATH3='/data/coeus/data/man/'
DATAPATH='/data/coeus/import/cu/'
DATAPATH2='/data/coeus/import/4g/'
DATAPATH3='/data/coeus/import/man/'
CONTROLPATH=WORKPATH + '/control/coeus'


def sqlldrfunc(CTLFILE, DATAFILE, FILENAME):
	cmd='sqlldr '+USERNAME+'/'+PASSWORD+'@'+TNS_NAME+' control='+CONTROLPATH+'/'+CTLFILE+' data='+DATAFILE+' log='+LOGPATH+'/'+FILENAME+'.log bad='+LOGPATH+'/'+FILENAME+'.bad rows=1000'
	logger1.info(cmd)
	RET=commands.getstatusoutput(cmd)
	logger1.info(RET)
    #if STATUS == 0:
    #    os.remove(DATAFILE)

def deletefile(DATAFILE):
    if(os.path.isfile(DATAFILE)):
        os.remove(FILE) 
        
def scanfile(FILENAME,CONTROLFILE,INPUTPATH):
	list = os.listdir(INPUTPATH) #list all file dir
	for f in list:
		filepath = os.path.join(INPUTPATH,f)
		if(os.path.isfile(INPUTPATH + '/' + f)):
			sqlldrfunc(CONTROLFILE,filepath,FILENAME)
        deletefile(filepath)
            

def delete():
	list = os.listdir(DATAPATH) #list all file dir
	for f in list:
		filepath = os.path.join(DATAPATH,f)
		if(os.path.isfile(DATAPATH + '/' + f)):
			os.remove(filepath)
            
           
            
if __name__ == '__main__':  
	cmd='/bin/mv ' + SOURCEPATH + '*.txt ' + DATAPATH
#	cmd2='/bin/mv ' + SOURCEPATH2 + '*.txt ' + DATAPATH2
#	cmd3='/bin/mv ' + SOURCEPATH3 + '*.txt ' + DATAPATH3
	
	logger1.info(cmd)
	RET=commands.getstatusoutput(cmd)
	logger1.info(RET)
	
#	logger1.info(cmd2)
#	RET2=commands.getstatusoutput(cmd2)
#	logger1.info(RET2)

#	logger1.info(cmd3)
#	RET3=commands.getstatusoutput(cmd3)
#	logger1.info(RET3)
    
	scanfile('cu','cuInfo.ctl',DATAPATH)
#	scanfile('4g','4gInfo.ctl',DATAPATH2)
#	scanfile('man','manInfo.ctl',DATAPATH3)
	
	delete()
	print 'COMPLATE'
